//
//  LGAccountTool.m
//  微博
//
//  Created by MS on 15-12-6.
//  Copyright (c) 2015年 MS. All rights reserved.


#import "LGAccountTool.h"
#import "LGAccount.h"
#import "LGHttpTool.h"
#import "AFNetworking.h"
#import "LGAccountParama.h"
#import "MJExtension.h"
#define LGAccountFile [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"account.data"]




//类方法一般用静态变量代替成员属性
static LGAccount * _account;

@implementation LGAccountTool

+(void) saveAccount:(LGAccount *)account
{
    
     [NSKeyedArchiver archiveRootObject:account toFile:LGAccountFile];
}

+(LGAccount *) account
{
    if (_account==nil) {
        
         _account =  [NSKeyedUnarchiver unarchiveObjectWithFile:LGAccountFile];
        
        //判断账号是否过期，如果过期返回0
        if ([[NSDate date] compare:_account.expires_date]!=NSOrderedAscending) {//过期
          
            _account =nil;
            
        }
        
    }
   
    return _account;
}


+(void)accessTokenWithCode:(NSString *)code  success:(void(^)())success failure:(void(^)(NSError *error))failure
{
   LGAccountParama * pamara = [[LGAccountParama alloc] init];
    pamara.client_id =LGclient_id;
    pamara.client_secret =LGclient_secret;
    pamara.grant_type =@"authorization_code";
    pamara.code =  code;
    pamara.redirect_uri =LGredirect_uri;
    
    [LGHttpTool POST:@"https://api.weibo.com/oauth2/access_token" parameters:[pamara keyValues]  success:^(id responseObject) {
        //字典转模型
        LGAccount * account = [LGAccount accountWithDic:responseObject];
        
        //保存账号信息：数据存储一般开发会搞个业务类，专门处理数据
        //不想用归档，可以在业务类里面更改方式
        
        [LGAccountTool saveAccount:account];
        if (success) {
            success();
        }

    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];

}

@end
